<?php
/**
 * Created by PhpStorm.
 * User: Jason
 * Date: 2017/7/28
 * Time: 16:03
 */

namespace Api\Service;


class ScoreSheetService
{
    /**
     * 添加用户收藏曲谱至谱单
     * @param $param
     */
    public function addSheetToScore($param)
    {
        $model = M('ScoreSheet');
        //判断该关系是否存在
        $map = array(
            'score_id' => $param['score_id'],
            'sheet_id' => $param['sheet_id']
        );
        $res = $model->where($map)->select();
        if ($res) {
            if ($res[0]['is_delete']) {
                $data = array('is_delete'=>0);
                $res = $model->where($map)->save($data);

                //谱单曲谱数记录+1
                M('Score')->where(array('id'=>$param['score_id']))->setInc('sheet_count');
                //曲谱收藏数+1
                M('Sheet')->where(array('id'=>$param['sheet_id']))->setInc('fav_count');
            } else {
                return false;
            }
            return $res;
        } else {
            $data = $model->create($param);
            if ($data) {
                $param['creator'] = $param['uid'];
                $param['create_time'] = date('Y-m-d H:i:s', time());
                $id = $model->add($param);

                //谱单曲谱数记录+1
                M('Score')->where(array('id'=>$param['score_id']))->setInc('sheet_count');
                //曲谱收藏数+1
                M('Sheet')->where(array('id'=>$param['sheet_id']))->setInc('fav_count');

                return $id;
            } else {
                E($model->getError());
            }
        }
    }

    /**
     * 将曲谱从谱单中删除
     */
    public function delFromScore($param)
    {
        //判断用户是否谱单创建者
        $creator = M('Score')->where(array('id'=>$param['score_id']))->getField('creator');
        if ($creator != $param['uid']) {
            return false;
        }
        $model = M('ScoreSheet');
        $map = array(
            'score_id' => $param['score_id'],
            'sheet_id' => $param['sheet_id']
        );
        $data = array(
            'is_delete' => 1
        );
        $res = $model->where($map)->save($data);

        //谱单曲谱数记录-1
        M('Score')->where(array('id'=>$param['score_id']))->setDec('sheet_count');

        //曲谱收藏数-1
        M('Sheet')->where(array('id'=>$param['sheet_id']))->setDec('fav_count');

        return $res;
    }
}